{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "df1ee7b6",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "#读取数据\n",
    "dataset=pd.read_csv('item8-ss-data-y.csv')\n",
    "print('“泰坦尼克号”乘客信息数据集')\n",
    "print(dataset)\n",
    "#显示数据集信息\n",
    "dataset.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23f89561",
   "metadata": {},
   "outputs": [],
   "source": [
    "#删除name列、ticket列和room列\n",
    "dataset.drop(['name','ticket','room'],inplace=True,axis=1)\n",
    "#补充age列的缺失值（用平均值进行补充）\n",
    "dataset['age']=dataset['age'].fillna(dataset['age'].mean())\n",
    "#删除有缺失值的所有行\n",
    "dataset=dataset.dropna()\n",
    "#将pclass列转换为数值型数据，分别用0、1和2代替\n",
    "labels=dataset['pclass'].unique().tolist()\n",
    "dataset['pclass']=dataset['pclass'].apply(lambda x:labels.index(x))\n",
    "#将sex列转换为数值型数据，分别用0和1代替\n",
    "dataset['sex']=(dataset['sex']=='male').astype(int)\n",
    "#将embarked列转换为数值型数据，分别用0、1和2代替\n",
    "labels=dataset['embarked'].unique().tolist()\n",
    "dataset['embarked']=dataset['embarked'].apply(lambda x:labels.index(x))\n",
    "print(dataset)\n",
    "dataset.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eb321465",
   "metadata": {},
   "outputs": [],
   "source": [
    "#调节随机森林算法的n_estimators参数，并画出对应的学习曲线\n",
    "from sklearn.ensemble import RandomForestClassifier \n",
    "from sklearn.metrics import accuracy_score\n",
    "from sklearn.model_selection import train_test_split\n",
    "import matplotlib.pyplot as plt\n",
    "#提取特征变量与标签\n",
    "x=dataset.iloc[range(0,821),range(0,4)].values\n",
    "y=dataset.iloc[range(0,821),range(4,5)].values.reshape(1,821)[0]\n",
    "x_train,x_test,y_train,y_test=train_test_split(x,y,\n",
    "random_state=1,test_size=0.2)\n",
    "score=[]\n",
    "for i in range(0,200,10):\n",
    "    model=RandomForestClassifier(random_state=0,n_estimators=i+1)\n",
    "     model= model.fit(x_train,y_train)\n",
    "     pred=model.predict(x_test)\n",
    "     ac=accuracy_score(y_test,pred)\n",
    "     score.append(ac)\n",
    "print('最大预测准确率为：%f'%max(score))\n",
    "n=score.index(max(score))*10+1\n",
    "print('预测准确率最大的模型对应的参数值为：%.0f'%n)\n",
    "plt.plot(range(1,201,10),score)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d5c7a4f8",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import classification_report\n",
    "model=RandomForestClassifier(random_state=0,n_estimators=41)\n",
    "model.fit(x_train,y_train)\n",
    "pred=model.predict(x_test)\n",
    "re=classification_report(y_test,pred)\n",
    "print('模型评估报告：')\n",
    "print(re)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e9f704da",
   "metadata": {},
   "outputs": [],
   "source": [
    "test=pd.read_csv('item8-ss-test-y.csv')\n",
    "print('需预测数据')\n",
    "print(test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94bb595d",
   "metadata": {},
   "outputs": [],
   "source": [
    "#处理数据\n",
    "#将pclass列转换为数值型数据，分别用0、1和2代替\n",
    "labels=test['pclass'].unique().tolist()\n",
    "test['pclass']=test['pclass'].apply(lambda x:labels.index(x)) \n",
    "#将sex列转换为数值型数据，分别用0和1代替\n",
    "test['sex']=(test['sex']=='male').astype(int)\n",
    "#将embarked列转换为数值型数据，分别用0、1和2代替\n",
    "labels=test['embarked'].unique().tolist()\n",
    "test['embarked']=test['embarked'].apply(lambda x:labels.index(x)) \n",
    "print(test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d6e44775",
   "metadata": {},
   "outputs": [],
   "source": [
    "x_new=test.iloc[range(0,14),range(0,4)].values  \n",
    "names=test.iloc[range(0,14),range(4,5)].values  \n",
    "pred=model.predict(x_new)\n",
    "for result,name in zip(pred,names):\n",
    "if result==1:\n",
    "print(name+\"能够获救\")\n",
    "else:\n",
    "print(name+\"不能获救\")"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
